// 智慧种菜项目的状态管理模块
import { 
  listTenancy, getTenancy, addTenancy, updateTenancy, delTenancy,
  listCrop, getCrop, buyCrop, plantCrop,
  waterCrop, fertilizeCrop, weedCrop, deinsectizeCrop, harvestCrop,
  getWeather, listFriends, addFriend, getChatHistory, sendChatMessage
} from '@/api/farming'

const farming = {
  namespaced: true,
  state: {
    // 田地相关
    tenancies: [],         // 用户的田地列表
    currentTenancy: null,  // 当前选中的田地
    
    // 作物相关
    crops: [],             // 作物列表
    userCrops: [],         // 用户已购买的作物/种子
    
    // 天气相关
    weather: null,         // 当前天气信息
    
    // 好友聊天相关
    friends: [],           // 好友列表
    currentFriend: null,   // 当前选中的好友
    chatHistory: [],       // 聊天记录
  },

  mutations: {
    // 田地相关
    SET_TENANCIES(state, tenancies) {
      state.tenancies = tenancies;
    },
    SET_CURRENT_TENANCY(state, tenancy) {
      state.currentTenancy = tenancy;
    },
    ADD_TENANCY(state, tenancy) {
      state.tenancies.push(tenancy);
    },
    UPDATE_TENANCY(state, tenancy) {
      const index = state.tenancies.findIndex(item => item.tenancyId === tenancy.tenancyId);
      if (index !== -1) {
        state.tenancies.splice(index, 1, tenancy);
      }
    },
    REMOVE_TENANCY(state, tenancyId) {
      state.tenancies = state.tenancies.filter(item => item.tenancyId !== tenancyId);
    },
    
    // 作物相关
    SET_CROPS(state, crops) {
      state.crops = crops;
    },
    SET_USER_CROPS(state, crops) {
      state.userCrops = crops;
    },
    ADD_USER_CROP(state, crop) {
      state.userCrops.push(crop);
    },
    
    // 田地操作相关
    UPDATE_CROP_STATUS(state, { tenancyId, cropId, data }) {
      if (state.currentTenancy && state.currentTenancy.tenancyId === tenancyId) {
        // 更新当前田地的作物状态
        if (state.currentTenancy.crops) {
          const cropIndex = state.currentTenancy.crops.findIndex(c => c.cropId === cropId);
          if (cropIndex !== -1) {
            state.currentTenancy.crops[cropIndex] = { ...state.currentTenancy.crops[cropIndex], ...data };
          }
        }
      }
    },
    
    // 天气相关
    SET_WEATHER(state, weather) {
      state.weather = weather;
    },
    
    // 好友聊天相关
    SET_FRIENDS(state, friends) {
      state.friends = friends;
    },
    SET_CURRENT_FRIEND(state, friend) {
      state.currentFriend = friend;
    },
    SET_CHAT_HISTORY(state, history) {
      state.chatHistory = history;
    },
    ADD_CHAT_MESSAGE(state, message) {
      state.chatHistory.push(message);
    },
    ADD_FRIEND(state, friend) {
      state.friends.push(friend);
    }
  },

  actions: {
    // 获取用户的田地列表
    getTenancies({ commit }, query) {
      return new Promise((resolve, reject) => {
        listTenancy(query).then(response => {
          commit('SET_TENANCIES', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 获取田地详情
    getTenancyDetail({ commit }, tenancyId) {
      return new Promise((resolve, reject) => {
        getTenancy(tenancyId).then(response => {
          commit('SET_CURRENT_TENANCY', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 新增田地
    addTenancyAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        addTenancy(data).then(response => {
          commit('ADD_TENANCY', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 修改田地信息
    updateTenancyAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        updateTenancy(data).then(response => {
          commit('UPDATE_TENANCY', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 删除田地
    delTenancyAction({ commit }, tenancyId) {
      return new Promise((resolve, reject) => {
        delTenancy(tenancyId).then(response => {
          commit('REMOVE_TENANCY', tenancyId);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 获取作物列表
    getCrops({ commit }, query) {
      return new Promise((resolve, reject) => {
        listCrop(query).then(response => {
          commit('SET_CROPS', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 购买种子（作物）
    buyCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        buyCrop(data).then(response => {
          commit('ADD_USER_CROP', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 播种（将作物种植到田地）
    plantCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        plantCrop(data).then(response => {
          // 更新田地状态
          commit('UPDATE_TENANCY', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 浇水
    waterCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        waterCrop(data).then(response => {
          commit('UPDATE_CROP_STATUS', {
            tenancyId: data.tenancyId,
            cropId: data.cropId,
            data: response.data
          });
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 施肥
    fertilizeCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        fertilizeCrop(data).then(response => {
          commit('UPDATE_CROP_STATUS', {
            tenancyId: data.tenancyId,
            cropId: data.cropId,
            data: response.data
          });
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 除草
    weedCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        weedCrop(data).then(response => {
          commit('UPDATE_CROP_STATUS', {
            tenancyId: data.tenancyId,
            cropId: data.cropId,
            data: response.data
          });
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 除虫
    deinsectizeCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        deinsectizeCrop(data).then(response => {
          commit('UPDATE_CROP_STATUS', {
            tenancyId: data.tenancyId,
            cropId: data.cropId,
            data: response.data
          });
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 收获作物
    harvestCropAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        harvestCrop(data).then(response => {
          commit('UPDATE_CROP_STATUS', {
            tenancyId: data.tenancyId,
            cropId: data.cropId,
            data: response.data
          });
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 获取天气信息
    getWeatherAction({ commit }, location) {
      return new Promise((resolve, reject) => {
        getWeather(location).then(response => {
          commit('SET_WEATHER', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 获取好友列表
    getFriends({ commit }) {
      return new Promise((resolve, reject) => {
        listFriends().then(response => {
          commit('SET_FRIENDS', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 添加好友
    addFriendAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        addFriend(data).then(response => {
          commit('ADD_FRIEND', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 获取聊天记录
    getChatHistoryAction({ commit }, friendId) {
      return new Promise((resolve, reject) => {
        getChatHistory(friendId).then(response => {
          commit('SET_CHAT_HISTORY', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 发送聊天消息
    sendChatMessageAction({ commit }, data) {
      return new Promise((resolve, reject) => {
        sendChatMessage(data).then(response => {
          commit('ADD_CHAT_MESSAGE', response.data);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },
    
    // 设置当前选中的好友
    setCurrentFriend({ commit }, friend) {
      commit('SET_CURRENT_FRIEND', friend);
    }
  }
};

export default farming;